package com.bsoft.exchange.service;

import com.bsoft.exchange.dao.his.PatientMapper;
import com.bsoft.exchange.dao.his.SystemConfigMapper;
import com.bsoft.exchange.dao.portal.GyBrdaDomainMapper;
import com.bsoft.exchange.domain.Invoice;
import com.bsoft.exchange.domain.InvoiceDomain;
import com.bsoft.exchange.domain.PatientDomain;
import com.bsoft.exchange.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PatientService {
	
	public static final String FormatStr ="yyyy-MM-dd";
	
	@Autowired
	PatientMapper patientMapper;
	@Autowired
	IdentityManager identityManager;
	//@Autowired
	//UserBillMapper userBillMapper;
	@Autowired
	UserBillManager userBillManager;

	@Autowired
	GyBrdaDomainMapper gyBrdaDomainMapper;

	@Autowired
	SystemConfigMapper systemConfigMapper;


	public BaseResponse<List<InvoiceDomain>> getInvoiceList(String idCard){
		BaseResponse<List<InvoiceDomain>> baseResponse = new BaseResponse<>();
		List<Invoice> invoiceList = patientMapper.getInvoiceList(idCard);
		List<InvoiceDomain> invoiceDomains = invoiceList.stream().map(invoice -> {
			InvoiceDomain invoiceDomain = new InvoiceDomain();
			invoiceDomain.setPatientName(invoice.getPatientName());
			invoiceDomain.setHospitalName(invoice.getHospitalName());
			invoiceDomain.setInvoiceNumber(invoice.getInvoiceNumber());
			invoiceDomain.setPatientStyle(invoice.getPatientStyle());
			invoiceDomain.setPayAmount(invoice.getPayAmount());
			invoiceDomain.setPayTime(DateUtil.dateFormat(invoice.getPayTime()));
			invoiceDomain.setUrl(invoice.getUrl());
			return invoiceDomain;
		}).collect(Collectors.toList());
		baseResponse.setData(invoiceDomains);
		return baseResponse;
	}

	
	@Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
	public Map<String, Object> getPhoneAndCards(
			String hospitalCode, 
			Integer patientIdentityCardType,
			String patientIdentityCardNumber,
			Integer patientMedicalCardType,
			String patientMedicalCardNumber,
			String patientName,
			Integer patientSex,
			String patientBirthday,
			String patientMobile,
			String provinceCode,
			String cityCode,
			String areaCode,
			String patientAddress,
			Integer operationType){
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		Map<String, Object> ret = new HashMap<String, Object>();
		
		Long jgid;
		Long sbxh;
		jgid = 1L;
		param.put("jgid", jgid);
		//默认查询
		if(operationType == null){
			operationType = 1;
		}
		Date csny =null ;
		String error = "";
		
		/*param.put("lxdh", patientMobile);
		param.put("xzz_sqs", provinceCode);
		param.put("xzz_s", cityCode);
		param.put("xzz_x", areaCode);
		param.put("xzz_qtdz", patientAddress);*/
		
		List<PatientDomain> patientList  = new ArrayList();
		Long brid;
		String mzhm = "";

		if(patientIdentityCardType!=null){
			
			//1为身份证
			if(patientIdentityCardType == 1){
				
				param.put("sfzh", patientIdentityCardNumber);
				
				if(patientIdentityCardNumber!=null && !"".equals(patientIdentityCardNumber) && operationType ==2){
					patientList = patientMapper.getPhoneAndCards(param);
					if(patientList !=null && patientList.size() >0 ){
						
						ret.put("patientList", patientList);
						ret.put("ywlx", "建档");  
						ret.put("error", "档案已存在！");
						
						return ret;
					}
				}

			}else{
				//证件类型和号码
				param.put("zjlx", patientIdentityCardType);
				param.put("zjhm", patientIdentityCardNumber);
			}

		}
		
		param.put("brxm", patientName);
		param.put("brxb", patientSex);
		
		if(patientBirthday!= null && !"".equals(patientBirthday) && !"string".equals(patientBirthday)){
			csny = DateUtil.StrToFormatDate(patientBirthday, FormatStr);
			param.put("csny", csny);
		}
		
		
		
		/*已有患者档案信息（有至少一张卡）：
		1、姓名、性别、证件信息、手机号码
		2、姓名、性别、手机号码
		3、姓名、证件信息、就诊卡信息*/
		
		String ywlx = "";
		// operationType 1查询 2 建档
		if(operationType == 1){
			
			//有卡时直接根据 卡、姓名、性别、身份证 出生年月查询
			if(patientMedicalCardType!=null && patientMedicalCardNumber !=null && !"".equals(patientMedicalCardNumber)){
				
				ywlx = "卡查询";
				if(patientMedicalCardType == 5){
					param.put("zyhm", patientMedicalCardNumber);
					patientList = patientMapper.getPhoneAndCardsInHospital(param);
				}else{
					if(patientMedicalCardType == 2){
						param.put("jzkh", patientMedicalCardNumber);
					}
					if(patientMedicalCardType == 3){
						param.put("ybkh", patientMedicalCardNumber);
					}
					
					patientList = patientMapper.getPhoneAndCards(param);

				}
	
			}else{    //无卡时,无电话直接返回，有电话 根据 姓名、性别、身份证 出生年月查询，有一样电话返回卡信息  
					  //后调整 无电话一样查
				
				ywlx = "电话号码查询";
//				if(patientMobile!=null && !"".equals(patientMobile)){
					param.put("lxdh", patientMobile);
					patientList = patientMapper.getPhoneAndCards(param);
					
					/*if(patientList!=null && patientList.size() > 0){
						for(PatientDomain patient: patientList){
							
							if(patient.getLxdh() == null ){
								patientList.remove(patient);
								continue;
							}
							//不等的移除
							if(!patientMobile.equals(patient.getLxdh()) ){
								patientList.remove(patient);
								continue;
							}
						}
					}*/
//				}
				
				
			}
		/*}else if(operationType == 2){
				
			ywlx = "修改电话号码";
			patientList = patientMapper.getPhoneAndCards(param);
			
			if(patientList!=null && patientList.size() == 1){
				PatientDomain patient = patientList.get(0);
				
				patient.setLxdh(patientMobile);
				patient.setXgsj(new Date());
				patientMapper.updatePatient(patient);
				patientList.add(patient);
			}*/

		}else if(operationType == 2){
				
			ywlx = "建档";
			PatientDomain patient = new PatientDomain();
			
			param.put("lxdh", patientMobile);
			
			patientList = patientMapper.getPhoneAndCards(param);
			
			if(patientList!=null && patientList.size() > 0){
				
				error = "档案已存在!";
			}else{
				brid = identityManager.getMax("MS_BRDA", 1);
				mzhm = userBillManager.getMzhm(jgid,"");
				
				patient.setBrid(brid);
				patient.setBrxb(patientSex);
				patient.setBrxm(patientName);
				patient.setCsny(csny);
				patient.setMzhm(mzhm);
				patient.setLxrm(patientName);
				patient.setLxdh(patientMobile);
				
				if(patientIdentityCardType!=null){
					if(patientIdentityCardType == 1){
						patient.setSfzh(patientIdentityCardNumber);
					}
					patient.setZjlx(patientIdentityCardType.longValue());
					patient.setZjhm(patientIdentityCardNumber);
				}

				//2就诊卡号 3医保卡号
				if(patientMedicalCardType!=null){
					if(patientMedicalCardType == 2){
						patient.setJzkh(patientMedicalCardNumber);
					}
					if(patientMedicalCardType == 3){
						patient.setYbkh(patientMedicalCardNumber);
					}
				}
				if(provinceCode!=null && !"".equals(provinceCode)){
					patient.setXzz_sqs(Long.parseLong(provinceCode));
				}
				if(cityCode!=null && !"".equals(cityCode) ){
					patient.setXzz_s(Long.parseLong(cityCode));
				}
				if(areaCode!=null && !"".equals(areaCode) ){
					patient.setXzz_x(Long.parseLong(areaCode));
				}
				patient.setXzz_qtdz(patientAddress);
				Date jdsj = new Date();
				patient.setJdjg(jgid);
				patient.setJdsj(jdsj);
				patient.setXgsj(jdsj);
				patient.setJdr("900001");
				patient.setZxbz(0);
				
				String mrxz = systemConfigMapper.getValueByConfigName((long)0, "MRXZ"); //默认性质  his里不区分机构
				if(mrxz == null || "".equals(mrxz)){
					mrxz = "1000";
				}
				
				patient.setBrxz(Long.parseLong(mrxz));  //默认自费？
				patient.setXzmc("自费");
				
				patientMapper.savePatient(patient);
				userBillManager.updateMzhm(jgid,"",mzhm);

				//根据参数是否同步到门户GY_BRDA
				String tbbrda = systemConfigMapper.getValueByConfigName((long)0, "TBBRDA"); //同步病人档案  his里不区分机构
				if("1".equals(tbbrda)){
					gyBrdaDomainMapper.insert(patient);
				}
				patientList.add(patient);
			}

		}
		
		ret.put("patientList", patientList);
		ret.put("ywlx", ywlx);  //业务类型
		ret.put("error", error);
		
		return ret;
	}
	
	public BaseResponse<List<PatientDomain>> queryBusCards(	String hospitalCode, String patientCode){
			
		 	BaseResponse<List<PatientDomain>>baseResponse=new BaseResponse<>();
			Long brid ;
			
			String[] bridList;
			patientCode = patientCode.replace("，", ",");
	        bridList = patientCode.split(",");  
	        
	        Map<String, Object> param = new HashMap<String, Object>();
	        //param.put("jgid", jgid);
	        param.put("bridList", bridList);
			
//			brid = Long.parseLong(patientCode);
//			PatientDomain  patient = patientMapper.getPatientById(brid);
	        List<PatientDomain> patientList = patientMapper.getPatientByIdList(param);
	        
	        if(patientList == null || patientList.size() < 1){
	        	baseResponse.setCode(Constant.breakTag);
	            baseResponse.setMessage("未查询到该病人识别的数据!");
	            
	            return baseResponse;
	        }
	        baseResponse.setCode(Constant.successTag);
	        baseResponse.setData(patientList);
	        
			return baseResponse;
		
	}
	
//	public String getMzhm(Long jgid,String czgh){
//		
//		String mzhm = "MZCS";
//		mzhm = mzhm + identityManager.getMax("MS_MZHM", 1);
//		
//		//默认工号
//		if(czgh==null || "".equals(czgh)){
//			czgh = "1000025";   //100040  1000025
//		}
//
//		List<UserBillDomain> userBillList = userBillMapper.getUserBillList(jgid,czgh);
//		
//		//无票据
//		if(userBillList == null || userBillList.size() <= 0){
//			mzhm = "";
//			return mzhm;
//		}
//		
//		//LYRQ升序排序 取第一个
//		UserBillDomain  userBill = userBillList.get(0);
//		
//		mzhm = userBill.getSyhm();
//		
//		
//		return mzhm;
//	}
//	
//	public void updateMzhm(Long jgid,String czgh,String dqhm){
//		
//		//默认工号
//		if(czgh==null || "".equals(czgh)){
//			czgh = "1000025"; //100040  1000025
//		}
//
//		List<UserBillDomain> userBillList = userBillMapper.getUserBillList(jgid,czgh);
//		
//		String zzhm;
//		String syhm;
//		int end ;
//		Integer sypb = 0;
//		String dqhmPrefix;
//		Long dqhmHm;
//		String dqhmHmS;
//		Integer hmLen ;
//		//票据
//		if(userBillList != null && userBillList.size() > 0){
//			//LYRQ升序排序 取第一个
//			UserBillDomain  userBill = userBillList.get(0);
//			zzhm = userBill.getZzhm();
//			
//			//当前号码+1
//			end = 0;
//			for(int i= dqhm.length() - 1;i>=0;i--){
//				if(dqhm.charAt(i)>=48 && dqhm.charAt(i)<=57){
//					  continue;
//				  }else{
//					  
//					  end = i;
//					  break;
//				  }
//			}
//			
//			dqhmPrefix = "";
//			dqhmHmS = dqhm;
//			
//			if(end > 0 ){
//				dqhmPrefix = dqhm.substring(0,end + 1);
//				dqhmHmS = dqhm.substring(end + 1);
//			}
//
//			syhm = dqhmPrefix + String.format("%0" + dqhmHmS.length() + "d", Long.parseLong(dqhmHmS) + 1);
//			
//			if(syhm.compareTo(zzhm) > 0){
//				sypb = 1;
//			}
//			userBill.setJgid(jgid);
//			userBill.setYgdm(czgh);
//			userBill.setSyhm(syhm);
//			userBill.setSypb(sypb);
//			
//			userBillMapper.updateUserBill(userBill);
//		}
//
//	}
	
}
